CODE 13. Triangle

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/15/2013-09-15-CODE 13 Triangle/

访问原文「CODE 13. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 =
11).
Note:
Bonus point if you are able to do this using only O(n)
extra space, where n is
the total number of rows in the triangle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == triangle || 0 == triangle.size()) {
return 0;
}
int layerNumer = triangle.size();
ArrayList<Integer> tmpLengths = new ArrayList<Integer>();
tmpLengths.add(triangle.get(0).get(0));
for (int i = 1; i < layerNumer; i++) {
ArrayList<Integer> layer = triangle.get(i);
layer.set(0, layer.get(0) + tmpLengths.get(0));
for (int k = 1; k < layer.size(); k++) {
if (k == layer.size() - 1) {
layer.set(k, layer.get(k) + tmpLengths.get(k - 1));
} else {
if (tmpLengths.get(k) > tmpLengths.get(k - 1)) {
layer.set(k, tmpLengths.get(k - 1) + layer.get(k));
} else {
layer.set(k, tmpLengths.get(k) + layer.get(k));
}
}
}
tmpLengths.clear();
tmpLengths.addAll(layer);
}
int min = tmpLengths.get(0);
for (int i = 1; i < layerNumer; i++) {
if (tmpLengths.get(i) < min) {
min = tmpLengths.get(i);
}
}
return min;
}
Jerky Lu wechat
欢迎加入微信公众号